import React, { useState, useCallback, useEffect } from 'react';
import { Modal, Upload, Button, message, Progress, Card, Typography, Tag, Alert, Spin } from 'antd';
import { InboxOutlined, FileTextOutlined, CloudUploadOutlined, RocketOutlined } from '@ant-design/icons';
import { ImportFormat } from '../../types';
import { projectApi } from '../../services/api';

const { Dragger } = Upload;
const { Title, Text, Paragraph } = Typography;

interface ImportModalV2Props {
  visible: boolean;
  onCancel: () => void;
  onSuccess: () => void;
}

const ImportModalV2: React.FC<ImportModalV2Props> = ({
  visible,
  onCancel,
  onSuccess
}) => {
  const [importFormats, setImportFormats] = useState<ImportFormat[]>([]);
  const [loadingFormats, setLoadingFormats] = useState(false);
  const [uploading, setUploading] = useState(false);
  const [uploadProgress, setUploadProgress] = useState(0);
  const [selectedFile, setSelectedFile] = useState<File | null>(null);
  const [dragActive, setDragActive] = useState(false);
  const [showSuccess, setShowSuccess] = useState(false);
  const [showError, setShowError] = useState(false);
  const [errorMessage, setErrorMessage] = useState('');

  // 从后端获取导入格式列表
  useEffect(() => {
    if (visible) {
      setLoadingFormats(true);
      projectApi.getImportFormats()
        .then(res => {
          setImportFormats(res.formats || []);
        })
        .catch(err => {
          console.error('Failed to load import formats:', err);
          // 如果加载失败，使用默认格式
          setImportFormats([{
            format: 'json',
            name: 'JSON文件',
            extensions: ['.json'],
            description: 'JSON数据格式文件'
          }]);
        })
        .finally(() => {
          setLoadingFormats(false);
        });
    }
  }, [visible]);

  const handleFileSelect = useCallback((file: File) => {
    const ext = file.name.substring(file.name.lastIndexOf('.')).toLowerCase();
    const matched = importFormats.find(x => x.extensions.includes(ext));
    
    if (!matched) {
      message.error('不支持的文件类型，请选择支持的文件格式');
      return false;
    }
    
    setSelectedFile(file);
    return false; // 阻止自动上传
  }, [importFormats]);

  const handleUpload = async () => {
    if (!selectedFile) {
      message.error('请先选择文件');
      return;
    }

    try {
      setUploading(true);
      setUploadProgress(0);
      
      // 模拟上传进度
      const progressInterval = setInterval(() => {
        setUploadProgress(prev => {
          if (prev >= 90) {
            clearInterval(progressInterval);
            return prev;
          }
          return prev + Math.random() * 20;
        });
      }, 200);

      const ext = selectedFile.name.substring(selectedFile.name.lastIndexOf('.')).toLowerCase();
      const matched = importFormats.find(x => x.extensions.includes(ext));
      
      if (!matched) {
        throw new Error('不支持的文件格式');
      }

      // 调用导入接口
      const res = await projectApi.importByUpload(selectedFile, matched.format);
      
      clearInterval(progressInterval);
      setUploadProgress(100);
      setShowSuccess(true);
      
      // 显示成功状态2秒后再关闭
      setTimeout(() => {
        message.success(res.message || '导入成功');
        setSelectedFile(null);
        setUploadProgress(0);
        setShowSuccess(false);
        onSuccess();
        onCancel();
      }, 2000);
      
    } catch (error: any) {
      const errorMsg = error?.response?.data?.detail || '导入失败，请检查文件格式';
      setErrorMessage(errorMsg);
      setShowError(true);
      setUploadProgress(0);
      setShowSuccess(false);
      
      // 导入失败时不自动关闭提示，让用户手动关闭
    } finally {
      setUploading(false);
    }
  };

  const getFileIcon = (format: string) => {
    switch (format) {
      case 'excel':
        return <FileTextOutlined style={{ color: '#52c41a', fontSize: '24px' }} />;
      case 'json':
        return <FileTextOutlined style={{ color: '#1890ff', fontSize: '24px' }} />;
      default:
        return <FileTextOutlined style={{ color: '#8c8c8c', fontSize: '24px' }} />;
    }
  };

  const formatFileSize = (bytes: number) => {
    if (bytes === 0) return '0 Bytes';
    const k = 1024;
    const sizes = ['Bytes', 'KB', 'MB', 'GB'];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
  };

  // 重置所有状态
  const resetStates = () => {
    setUploading(false);
    setUploadProgress(0);
    setSelectedFile(null);
    setShowSuccess(false);
    setShowError(false);
    setErrorMessage('');
  };

  // 当模态框关闭时重置状态
  React.useEffect(() => {
    if (!visible) {
      resetStates();
    }
  }, [visible]);

  return (
    <Modal
      title={
        <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
          <RocketOutlined style={{ color: '#722ed1' }} />
          <span>导入项目参数</span>
        </div>
      }
      open={visible}
      onCancel={onCancel}
      width={600}
      footer={[
        <Button key="cancel" onClick={onCancel} disabled={uploading}>
          取消
        </Button>,
        <Button
          key="upload"
          type="primary"
          onClick={handleUpload}
          loading={uploading}
          disabled={!selectedFile}
          icon={<CloudUploadOutlined />}
          style={{ background: '#722ed1', borderColor: '#722ed1' }}
        >
          {uploading ? '导入中...' : '开始导入'}
        </Button>
      ]}
      destroyOnClose
    >
      <div style={{ padding: '8px 0' }}>
        <Alert
          message="导入说明"
          description="选择符合要求的文件并上传，将导入对应的项目参数。"
          type="info"
          showIcon
          style={{ marginBottom: '24px' }}
        />

        {/* 支持格式说明 */}
        {loadingFormats ? (
          <div style={{ textAlign: 'center', padding: '40px 0' }}>
            <Spin size="large" />
            <div style={{ marginTop: '16px', color: '#8c8c8c' }}>正在加载可用格式...</div>
          </div>
        ) : (
          <Card size="small" style={{ marginBottom: '24px', background: '#f8f9fa' }}>
            <Title level={5} style={{ margin: '0 0 12px 0', color: '#262626' }}>
              支持的导入格式
            </Title>
            {importFormats.length === 0 ? (
              <Alert
                message="暂无可用格式"
                description="当前没有可用的导入格式，请稍后再试。"
                type="warning"
                showIcon
              />
            ) : (
              <div style={{ display: 'flex', gap: '12px', flexWrap: 'wrap' }}>
                {importFormats.map(format => (
                  <Card
                    key={format.format}
                    size="small"
                    style={{ 
                      width: '140px', 
                      height: '160px',
                      textAlign: 'center',
                      background: 'white',
                      border: '1px solid #e8e8e8',
                      display: 'flex',
                      flexDirection: 'column',
                      justifyContent: 'space-between'
                    }}
                  >
                    <div>
                      <div style={{ marginBottom: '8px' }}>
                        {getFileIcon(format.format)}
                      </div>
                      <Text strong style={{ fontSize: '12px' }}>{format.name}</Text>
                      <div style={{ marginTop: '4px' }}>
                        {format.extensions.map(ext => (
                          <Tag key={ext} color="purple">
                            {ext}
                          </Tag>
                        ))}
                      </div>
                    </div>
                    <Paragraph 
                      style={{ 
                        fontSize: '10px', 
                        color: '#8c8c8c', 
                        margin: '8px 0 0 0',
                        lineHeight: '1.3',
                        display: '-webkit-box',
                        WebkitLineClamp: 3,
                        WebkitBoxOrient: 'vertical',
                        overflow: 'hidden',
                        textOverflow: 'ellipsis'
                      }}
                    >
                      {format.description}
                    </Paragraph>
                  </Card>
                ))}
              </div>
            )}
          </Card>
        )}

        {/* 文件上传区域 - 只在没有选中文件时显示 */}
        {!selectedFile && (
          <div
            onDragEnter={() => setDragActive(true)}
            onDragLeave={() => setDragActive(false)}
          >
            <Dragger
              accept={importFormats.flatMap(f => f.extensions).join(',')}
              beforeUpload={handleFileSelect}
              showUploadList={false}
              disabled={uploading || loadingFormats}
              style={{
                border: `2px dashed ${dragActive ? '#722ed1' : '#d9d9d9'}`,
                borderRadius: '8px',
                background: dragActive ? '#f9f0ff' : '#fafafa',
                transition: 'all 0.3s ease'
              }}
            >
            <div style={{ padding: '40px 20px' }}>
              <InboxOutlined 
                style={{ 
                  fontSize: '48px', 
                  color: dragActive ? '#722ed1' : '#8c8c8c',
                  marginBottom: '16px',
                  transition: 'color 0.3s ease'
                }} 
              />
              <Title level={4} style={{ color: dragActive ? '#722ed1' : '#262626' }}>
                {dragActive ? '松开鼠标上传文件' : '点击或拖拽文件到此区域上传'}
              </Title>
              <Paragraph style={{ color: '#8c8c8c', margin: '8px 0' }}>
                支持单个文件上传，文件大小不超过 10MB
              </Paragraph>
            </div>
            </Dragger>
          </div>
        )}

        {/* 选中文件信息 */}
        {selectedFile && (
          <Card 
            size="small" 
            style={{ 
              marginTop: '16px',
              background: 'linear-gradient(135deg, #f9f0ff 0%, #f0f8ff 100%)',
              border: '1px solid #b37feb'
            }}
          >
            <div style={{ display: 'flex', alignItems: 'center', gap: '12px' }}>
              {getFileIcon(selectedFile.name.split('.').pop() || '')}
              <div style={{ flex: 1 }}>
                <Text strong style={{ color: '#722ed1' }}>{selectedFile.name}</Text>
                <div style={{ fontSize: '12px', color: '#8c8c8c', marginTop: '2px' }}>
                  {formatFileSize(selectedFile.size)}
                </div>
              </div>
              <div style={{ display: 'flex', gap: '8px' }}>
                <Button 
                  size="small" 
                  type="text" 
                  onClick={() => setSelectedFile(null)}
                  disabled={uploading}
                >
                  重新选择
                </Button>
                <Button 
                  size="small" 
                  type="text" 
                  danger
                  onClick={() => setSelectedFile(null)}
                  disabled={uploading}
                >
                  移除
                </Button>
              </div>
            </div>
          </Card>
        )}

        {/* 上传进度 */}
        {(uploading || showSuccess || showError) && (
          <div 
            className="import-progress-container"
            style={{ 
              marginTop: '16px',
              opacity: uploading || showSuccess || showError ? 1 : 0,
              transition: 'opacity 0.3s ease-in-out'
            }}
          >
            <Alert
              message={
                showSuccess ? "导入成功！" : 
                showError ? "导入失败" : 
                "正在导入文件，请稍候..."
              }
              type={showSuccess ? "success" : showError ? "error" : "info"}
              showIcon
              style={{ 
                marginBottom: '12px',
                transition: 'all 0.3s ease-in-out'
              }}
            />
            {!showError && (
              <Progress
                percent={Math.round(uploadProgress)}
                status={showSuccess ? 'success' : 'active'}
                strokeColor={showSuccess ? {
                  '0%': '#722ed1',
                  '100%': '#9254de',
                } : {
                  '0%': '#722ed1',
                  '100%': '#9254de',
                }}
                style={{
                  transition: 'all 0.3s ease-in-out'
                }}
              />
            )}
            {showSuccess && (
              <div style={{ 
                textAlign: 'center', 
                marginTop: '12px',
                color: '#722ed1',
                fontSize: '14px',
                fontWeight: '500',
                animation: 'fadeIn 0.5s ease-in-out'
              }}>
                文件导入完成，即将关闭窗口...
              </div>
            )}
            {showError && (
              <div style={{ 
                textAlign: 'center', 
                marginTop: '12px',
                color: '#ff4d4f',
                fontSize: '14px',
                fontWeight: '500',
                animation: 'fadeIn 0.5s ease-in-out',
                padding: '12px',
                background: '#fff2f0',
                border: '1px solid #ffccc7',
                borderRadius: '6px',
                position: 'relative'
              }}>
                <div style={{ marginBottom: '8px' }}>
                  {errorMessage}
                </div>
                <Button 
                  size="small" 
                  type="text" 
                  onClick={() => {
                    setShowError(false);
                    setErrorMessage('');
                  }}
                  style={{ 
                    color: '#ff4d4f',
                    fontSize: '12px'
                  }}
                >
                  关闭提示
                </Button>
              </div>
            )}
          </div>
        )}

        {/* 使用提示 */}
        <Alert
          message="导入说明"
          description={
            <div>
              <p>• 确保文件格式正确，包含完整的项目参数信息</p>
              <p>• 如果项目名称已存在，系统会自动添加副本标识</p>
              <p>• 导入完成后会自动刷新项目列表</p>
              <p>• 导入完成后，系统会在项目列表中显示新数据</p>
            </div>
          }
          type="info"
          showIcon
          style={{ marginTop: '16px' }}
        />
      </div>
    </Modal>
  );
};

export default ImportModalV2;

